package com.ljb.downloadmanager;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private String downloadUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadUrl = "http://114.215.144.168:8018/apkfile/new_apk/shukuang_v1.0.7.apk";

    }

    public void brows(View view) {
        browsDownload(downloadUrl);
    }

    public void dm(View view) {
        dmDownload(downloadUrl);
    }

    /**
     * 调用系统浏览器下载
     * @param downloadUrl
     */
    private void browsDownload(String downloadUrl) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(downloadUrl));
        startActivity(intent);
    }

    /**
     * 调用系统下载管理器下载
     * @param downloadUrl
     */
    private void dmDownload(String downloadUrl) {
        DMHelper helper = new DMHelper(App.getContext());
        helper.download(downloadUrl, new DMHelper.DMHelperListener() {
            @Override
            public void doSuccess() {
                Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                installApk();
            }

            @Override
            public void doError() {
                Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void installApk() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.parse("file://" + Uri.fromFile(DMHelper.saveFile)), "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
